package com.sangmo.fts.process.inventory.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.common.session.UserSession;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.basic.model.Goods;
import com.sangmo.fts.common.utils.RandomUtils;
import com.sangmo.fts.process.inventory.interfaces.IfInboundCreation;
import com.sangmo.fts.process.inventory.interfaces.IfOutboundDispatchRequest;
import com.sangmo.fts.process.inventory.model.IfLadingBill;
import com.sangmo.fts.process.inventory.model.IfLadingBillItem;
import com.sangmo.fts.process.inventory.model.IfOutbound;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class IfOutBoundService extends DelegateViewService<IfOutbound> {

    @Autowired
    private IfOutboundEntityService ifOutboundEntityService;

    @Autowired
    private IfInboundService ifInboundService;

    @Autowired
    private IfLadingBillEntityService ifLadingBillEntityService;

    @Autowired
    private IfLadingBillItemEntityService ifLadingBillItemEntityService;

    @Override
    protected ViewService<IfOutbound> getEntityService() {
        return ifOutboundEntityService;
    }

    public void dispatch(Long outboundId) {
        IfOutbound outbound = this.get(outboundId);
        if (!IfOutbound.States.PENDING.equals(outbound.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ifOutbound.dispatch.state.wrong");
        }
        outbound.setState(IfOutbound.States.COMPLETED);
        outbound.setDeliveryNo(RandomUtils.generateRandomNum(8));

        this.save(outbound);
        afterDispatch(outbound);
    }

    private void afterDispatch(IfOutbound outbound) {
        IfInboundCreation creation = new IfInboundCreation();
        creation.setTrainingId(outbound.getTrainingId());
        creation.setOutboundId(outbound.getId());
        ifInboundService.create(creation);
    }

    public PageResult<IfLadingBillItem> searchGoods(Long id, PageSearch ps) {
        IfOutbound outbound = this.get(id);
        ps.getFilters().add(new ValueFilter("billId", ValueFilter.OP_EQ, outbound.getBillId()));
        return ifLadingBillItemEntityService.search(ps);
    }

}
